from urllib import response
from django.shortcuts import render
from django.http import StreamingHttpResponse
from .forms import FileUploadForm
import os

from teachzero import settings
from home.views import user_check

# Create your views here.

base_dir=os.path.dirname(settings.BASE_DIR)
def readFile(filename, chunk_size=512):
    """
    缓冲流下载文件方法
    :param filename:
    :param chunk_size:
    :return:
    """
    with open(filename, "rb") as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break


def download(file):
    "下载文件"
    dirname, file_name = os.path.split(str(file))
    response = StreamingHttpResponse(readFile(file))
    response["Content-Type"] = "application/octet-stream"
    response["Content-Disposition"] = 'attachment;filename="{0}"'.format(
        file_name)
    return response


def index(request):
    "工具箱主页"
    context = user_check(request)
    context["title"] += "-工具箱"
    return render(request, "tools/index.html", context)


def share(request, messages={}):
    "临时共享主页"
    context = user_check(request)
    for key in messages:
        context[key] = messages[key]
    if request.user.is_superuser:
        context["superuser"] = request.user.username
    file_path = os.path.join(
        base_dir, "statics", "tools", "tools", "share")
    files = []
    for path, dirname, filenames in os.walk(file_path):
        for file in filenames:
            url = os.path.join(path, file)
            url = url[len(file_path):]
            url = url.split("/")
            url = os.path.join("static", "tools", "tools", "share", *url)
            dirname1 = os.path.dirname(os.path.join(path, file))
            dirname2 = os.path.dirname(dirname1)
            dirname = dirname1[len(dirname2) + 1:]
            files.append((file[:20], url, dirname))
    files = sorted(files, key=lambda x: (x[2], x[0]))
    keys = set([x[2] for x in files])
    keys = list(keys)
    keys.sort()
    new_files = [[] for i in keys]
    for file in files:
        i = keys.index(file[2])
        new_files[i].append(file)
    context["sharelist"] = new_files
    context["title"] += "-临时共享"
    return render(request, "tools/share.html", context)


def common(request):
    "常用软件主页"
    context = user_check(request)
    context["title"] += "-常用软件"
    return render(request, "tools/common.html", context)


def websites(request):
    "常用网站主页"
    context = user_check(request)
    context["title"] += "-常用网站"
    return render(request, "tools/websites.html", context)


def file_upload(request):
    "上传文件"
    context = user_check(request)
    if request.method == "POST":
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            file_name = handle_uploaded_file(request.FILES["file"], request)
            context["file_name"] = file_name
            context["title"] += "-上传成功"
            return render(request, "tools/upsuccess.html", context)
    else:
        form = FileUploadForm()
    context["form"] = form
    context["title"] += "-上传文件"
    return render(request, "tools/upload.html", context)


def handle_uploaded_file(file, request):
    "保存文件"
    file_name = file.name
    file_dir = os.path.join(
        base_dir,
        "statics",
        "tools",
        "tools",
        "share",
        request.user.username,
    )
    if not os.path.isdir(file_dir):
        os.makedirs(file_dir)
    file_path = os.path.join(file_dir, file_name)
    with open(file_path, "wb+") as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    return file_name


def delete(request, url):
    """删除文件"""
    messages = {}
    if request.user.is_superuser:
        file_path = url.split("static/")[-1]
        file_path = os.path.join(base_dir, "statics", file_path)
        os.system(f"rm -rf {file_path}")
        name = os.path.split(url)[-1]
        messages["message_success"] = f"【{name}】删除成功。"
    else:
        messages["message_danger"] = "对不起，你没有权限。"
    return share(request, messages)
